<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card>
          <el-select
            v-model="SearchType"
            placeholder="请选择查询字段"
            style="width: 15%"
          >
            <el-option label="学号" value="id"></el-option>
            <el-option label="姓名" value="username"></el-option>
            <el-option label="籍贯" value="address"></el-option>
            <el-option label="班级" value="classes"></el-option>
          </el-select>
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="SearchText"
            style="width: 20%"
          >
          </el-input>
          <el-button
            type="primary"
            size="small"
            style="margin-left: 10px"
            @click="searchUser"
            >搜索</el-button
          >
          <el-button
            type="primary"
            size="small"
            style="margin-left: 10px"
            @click="clear_search"
            >重置</el-button
          >

          <el-button
            type="primary"
            size="small"
            style="float: right"
            v-show="!show"
            color="#F56C6C"
            @click="show = !show"
            ><i class="el-icon-upload el-icon--left"></i>上传
          </el-button>
          <el-button
            type="primary"
            size="small"
            style="float: right"
            v-show="!show"
            color="#F56C6C"
            @click="submitOut"
            ><i class="el-icon-upload el-icon--left"></i>导出选中数据
          </el-button>
        </el-card>
        <transition name="el-zoom-in-top">
          <el-card class="box-card" v-show="show" style="margin-top: 10px">
            <div slot="header" class="clearfix" style="text-align: center">
              <span>上传excel表格（.xlsx）</span>
            </div>
            <div class="transition-box" style="display: flex; margin-top: 40px">
              <el-upload
                ref="upload"
                class="upload-demo"
                drag
                action
                multiple
                accept=".xlsx, .xls"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handle"
                style="margin: auto"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div
                  class="el-upload__tip"
                  slot="tip"
                  style="text-align: center"
                >
                  文件上传速度跟当前环境有关，请耐心等待
                  <el-row :gutter="20" style="margin-top: 10px">
                    <el-col :span="12">
                      <el-button
                        size="small"
                        @click="show = !show"
                        style="width: 100%"
                        >关闭
                      </el-button>
                    </el-col>
                    <el-col :span="12">
                      <el-button
                        size="small"
                        type="primary"
                        @click="importxlsx"
                        style="width: 100%"
                        >导入
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-upload>
            </div>

            <!--<form :action="imgpath" enctype="multipart/form-data" method="post" style="margin: auto">-->
            <!--<input type="file" name="upload" multiple="multiple"><br>-->
            <!--<input type="submit" value="Upload">-->
            <!--</form>-->
          </el-card>
        </transition>
        <el-card
          style="margin-top: 20px; margin-bottom: 5rem"
          v-if="show1 == false"
        >
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55">
            </el-table-column>
            <el-table-column align="center" prop="id" sortable label="学号">
            </el-table-column>
            <el-table-column align="center" prop="username" label="姓名">
            </el-table-column>
            <el-table-column align="center" prop="sex" label="性别">
            </el-table-column>
            <el-table-column align="center" prop="address" label="生源地">
            </el-table-column>
            <el-table-column align="center" label="管理的班级">
              <template slot-scope="scope">
                <el-tag
                  type="danger"
                  v-for="(item, index) in scope.row.classes"
                  :key="index"
                  >{{ item}}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column align="center" label="身份">
              老师
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  style="padding: 3px 0"
                  type="text"
                  @click="delUser(scope.$index, scope.row)"
                >
                  删除
                </el-button>
                <el-button
                  style="padding: 3px 0"
                  type="text"
                  @click="userEdit(scope.$index, scope.row)"
                >
                  编辑
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="text-align: center; margin-top: 20px">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="paginations.page_index"
              :page-sizes="paginations.page_sizes"
              :page-size="paginations.page_size"
              :layout="paginations.layout"
              :total="paginations.total"
            >
            </el-pagination>
          </div>
        </el-card>
        <el-card style="margin-top: 20px" v-else-if="show1">
          <el-page-header @back="goBack" content="详情页面"> </el-page-header>
          <br />
          <el-form
            ref="form"
            v-model="user"
            label-width="80px"
            style="width: 50%"
          >
            <el-form-item label="姓名">
              <el-input
                v-model="user.username"
                style="width: 40%"
                :placeholder="user.username"
              ></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="user.sex">
                <el-radio label="男"></el-radio>
                <el-radio label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="籍贯">
              <el-input
                v-model="user.address"
                style="width: 40%"
                :placeholder="user.address"
              ></el-input>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="userUpdata">提交修改</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import xlsx from 'xlsx'
import { readFile, character } from '../../util/util'
export default {
  data () {
    return {
      form: {
        username: '',
        sex: '',
        address: '',
      },
      SearchType: "username",
      show1: false,
      show: false,
      SearchText: '',
      UserToal: 0,
      currentPage: 1,

      tableData: [],
      paginations: {
        page_index: 1,   //当前位于哪页
        total: 0,        //总数
        page_size: 5,    //一页显示多少条
        page_sizes: [5, 10, 15, 20, 30],    //每页显示多少条
        layout: "total, sizes, prev, pager, next, jumper"    //翻页属性
      },
      user: '',
      dataObj: [],
      SelectionList: [],
      updataNum: 0,
      insertNum: 0,
      errorNum: 0,
      allTableDate: [],
      class_options: [],
      filterTable: [],
      class_value: '',
    }
  },

  created () {
    /**
     * 生命周期创建时先获取
     */
    this.getUser()
  },
  methods: {

    async getUser () {
      const { data: ref } = await this.$Axios.get('teacher/getUser')
      this.filterTable = ref
      this.allTableDate = ref
      this.teacherClass()
      this.setPaginations()
    },
    async teacherClass () {
      const { data: result } = await this.$Axios.get('teacher/teacherClass')
      console.log(result.data)
      if (result.code) {
        this.allTableDate.forEach(item => {
          item.classes = []
          result.data.forEach(i => {
            if (item.id == i.t_id) {
              item.classes.push(i.classes)
            }
          })
        });
      }
    },

    //设置分页数据
    setPaginations () {
      this.paginations.total = this.filterTable.length
      this.handleCurrentChange(this.paginations.page_index)
    },
    //当每页数据条数发生改变时触发
    handleSizeChange (page_size) {
      this.paginations.page_size = page_size
      this.setPaginations()

    },
    handleCurrentChange (page) {
      this.paginations.page_index = page
      //获取当前页
      let index = this.paginations.page_size * (page - 1)
      //数据的总数
      let nums = this.paginations.page_size * page

      let table = []
      for (let i = index; i < nums; i++) {
        if (this.filterTable[i]) {
          table.push(this.filterTable[i])
        }
      }
      this.tableData = table
    },

    //清空搜索框内容并重新加载数据
    clear_search () {
      this.tableData = this.filterTable = this.allTableDate
      console.log();
      this.paginations.total = this.tableData.length
      this.tableData = this.allTableDate.filter((item, index) => {
        return index < this.paginations.page_size
      })
    },


    /**
   * 分页搜索用户信息
   * ,输入内容
   * this.value,搜素类型
   * 页码大小
   * this.cuurPage 当前页数
   * this.tableData列表数据
   *   this.UserToal列表数量
   * */
    async searchUser () {
      if (!this.SearchText) this.$message.warning("请输入要搜索的关键字!!!!!!")
      else {
        const { data: result } = await this.$Axios.get('admin/getUsersByTypeAndChar', {
          params: {
            inputText: this.SearchText,
            CharType: this.SearchType,
            type: 'teacher'
          }
        })
        this.filterTable = result.data
        //设置分页数据
        this.setPaginations()

      }
    },


    /**
   * 弹窗操作(ui框架调用)删除用户
   * */
    delUser (index, row) {
      this.$confirm('此操作将继续, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data } = await this.$Axios.delete('teacher/delUserdata', {
          params: {
            u_id: row.id
          }
        })
        if (data.result.code == 200) {
          this.$message.success("删除成功!")
          this.getUser()
        } else {
          this.$message.error("删除失败!")
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 显示修改页面
    userEdit (index, row) {
      this.show1 = true;
      this.user = row;
    },
    handleSelectionChange (val) {
      this.SelectionList = val
    },
    //显示修改页面
    goBack () {
      this.show1 = false;
    },

    async userUpdata () {
      if (!this.user.username || !this.user.sex || !this.user.address) {
        this.$message.warning("不可为空")
      } else {
        const { data: result } = await this.$Axios.post('teacher/upUserdata', this.user)
        if (result.code == 200) {
          this.$message.success(result.msg)
          this.show1 = false
          this.form = {
            username: '',
            sex: '',
            address: '',
          },
            this.get()
        } else {
          this.$message.error(result.msg)
        }

      }
    },


    /**
     * 导入文件操作
     */
    importxlsx () {

      if (this.dataObj.length <= 0) this.$message.warning("请选择要导入的文件")
      else {
        this.$confirm("将文件导入,是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //需要把数据一条条传递给服务器
          let n = 0

          let send = async () => {
            if (n > this.dataObj.length - 1) {
              //都传完了
              this.$message.success(`插入成功了${this.insertNum}条 更新了${this.updataNum}条 错误${this.errorNum}条`)
              this.getUser()
              return
            }
            let { data } = await this.$Axios.post('teacher/setXlsxData', this.dataObj[n])
            if (data.code == 200) {
              this.insertNum += 1
            } else if (data.code == 201) {
              this.updataNum += 1
            } else {
              this.errorNum += 1
            }

            n++
            send()
          }
          send()


        }).catch(() => {
          this.$message({
            type: 'info',
            message: '文件导入已经取消'
          })
        })
        this.get(this.pageNum, this.cuurPage)
      }
    },
    /* 导出excel表格 */
    submitOut () {
      if (this.SelectionList.length <= 0) {
        this.$message.warning('请先选中数据')
        return
      }
      let arr = this.SelectionList.map((item) => {
        return {
          工号号: item.id,
          姓名: item.username,
          密码: item.password,
          性别: item.sex,
          生源地: item.address,
          邮箱: item.mailbox,
          班级: item.class_id,
          类型: item.type,
          创建时间: item.createtime,
          最后修改时间: item.modifytime,
        }
      })
      let sheet = xlsx.utils.json_to_sheet(arr),    //json转换为sheet
        book = xlsx.utils.book_new()    //c创建表格
      xlsx.utils.book_append_sheet(book, sheet, '学生信息表')
      xlsx.writeFile(book, `user${new Date().getTime()}.xlsx`)
    },


    //采集excel数据
    async handle (ev) {
      let file = ev.raw
      if (!file) return
      //读取file中的数据
      let data = await readFile(file)
      //用xlsx读取数据
      let workbook = xlsx.read(data, { type: 'binary' })
      //读取文件中第一个表的数据
      workbook = workbook.Sheets[workbook.SheetNames[0]]
      //读取到的文件转换为json格式
      data = xlsx.utils.sheet_to_json(workbook)
      //把读取出来的数据变为最后可以传递给服务器的数据
      let arr = []
      data.forEach(item => {
        let obj = {}
        for (let key in character) {
          if (!character.hasOwnProperty(key)) break
          let v = character[key]
          let text = v.text
          let type = v.type
          v = item[text] || ''
          type === 'string' ? (v = String(v)) : null
          type === 'number' ? (v = Number(v)) : null
          obj[key] = v
        }
        arr.push(obj)
      });
      this.dataObj = arr

    },





  },
}
</script>

<style scoped lang="scss">
</style>
